<template>
	<div id="work" v-loading="loading">
		<div id="work_title">
			<div class="work_title_div dashu_scrollbar">
				<!-- 挂载title -->
				<div class="work_title_much" v-for="item in contents" :key="item">
          <div class="work_title_much_title">
            <div class="work_title_much_title_div1" @click="updateTitle(item)">
                {{item.title}}
            </div>
            <div class="work_title_much_title_div2">
              {{item.createTime | toTime }}
            </div>
            <div class="work_title_much_title_div3">
              <el-tooltip content="编辑文件" placement="top">
                <span class="el-icon-edit" @click="showContent(item)" ></span>
              </el-tooltip>
              <el-tooltip content="删除文件" placement="top">
                <span class="el-icon-delete" @click="remove(item)"></span>
              </el-tooltip>
            </div>
          </div>
				</div>
			</div>
		</div>
    <!-- 编辑器 -->
		<div id="work_editor">
      <!-- @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)"
      -->
      <quill-editor v-model="contentInfo.content"
        :disabled="disabled"
        ref="myQuillEditor"
        :options="editorOption"
        @ready="onEditorReady($event)"
      >
      </quill-editor>
		</div>

    <!-- 添加 -->
    <div class="work_title_add" @click="showAddItem()">
      <el-tooltip content="添加文件" placement="top">
        <span class="el-icon-circle-plus"></span>
      </el-tooltip>
    </div>
    <!-- 保存 -->
    <div v-if="!disabled" class="work_title_save" @click="saveInfo()">
      <el-tooltip content="保存修改内容" placement="top">
        <span class="el-icon-upload"></span>
      </el-tooltip>
    </div>
	<!-- 加载更多 -->
	<div class="work_title_download" @click="loadPage()">
	  <el-tooltip content="加载更多" placement="top">
	    <span class="el-icon-sort-down"></span>
	  </el-tooltip>
	</div>
	
    <!-- title名称 -->
    <el-dialog title="请输入标题" :visible.sync="dialogFormVisible" >
      <el-input placeholder="请输入标题" v-model="titleInfo.title" clearable></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addItem()">确 定</el-button>
      </div>
    </el-dialog>


	</div>
  
</template>

<script type="application/ecmascript-6">
export default {
  name: "work",
  data() {
    return {
      contents: [],
      loading: true,
      pageInfo: {
        //分页对象
        pageNow: 1,
        pageSize: 12,
        type: 3
      },
      editorOption: {
        placeholder: "点击编辑之后可以输入正文...",
        modules: {
          toolbar: [
            // bold:粗体 italic:斜体 underline:下划线  strike:删除线
            ["bold", "italic", "underline", "strike"],
            // blockquote:引用  code-block:代码
            ["blockquote", "code-block"],
            // H1  H2
            [{ header: 1 }, { header: 2 }],
            //ordered:有序列表   bullet:无序列表
            [{ list: "ordered" }, { list: "bullet" }],
            // sub:下标  super:上标
            [{ script: "sub" }, { script: "super" }],
            // tab左   tab右
            [{ indent: -1 }, { indent: +1 }],
            // 左开头右开头
            // [{ direction: rtl }],
            // 字体大小控制
            //[{ "size": ["small", false, "large", "huge"] } ],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            // 字体调整
            // [{ "font": [] }],
            //字体颜色 和北京颜色
            [{ color: [] }, { background: [] }],
            [{ align: [] }],
            //[{"clean":true}],
            ["link", "image"] //"video"
          ]
        }
      },
      contentInfo: {
        // 修改内容的实体
        content: ""
      },
      token: "",
      userInfo: {},
      dialogFormVisible: false,
      titleInfo: {
        title: ""
      },
      //修改title的实体 或者添加新文件的实体
      disabled: true
    };
  },
  created() {
    var tokenData = localStorage.getItem("token");
    var jsonO = JSON.parse(tokenData);
    var ui = this.$store.getters.getUserInfo
      ? this.$store.getters.getUserInfo
      : jsonO
        ? jsonO.userInfo
        : null;
    if (!ui) {
      this.$notify({
        message: "没有登陆，不可以发表文章"
      });
      this.$router.push("/home");
      return;
    }
    if (!jsonO) {
      this.$notify({
        message: "没有登陆，不可以发表文章"
      });
      this.$router.push("/home");
      return;
    }
    this.token = jsonO.token;
    this.userInfo = ui;
    this.loadPage();
  },
  methods: {
    loadPage: function() {
      this.$http
        .get("/api/content/findAll/" + this.pageInfo.type, {
          params: this.pageInfo,
          headers: {
            token: this.token
          }
        })
        .then(
          response => {
            if (response.body.code == 1) {
              this.$notify({
                message: response.body.msg
              });
              this.$router.push("/home");
              return;
            }
            this.loading = false;
            this.contents = this.contents.concat(response.body.data.content);
            this.pageInfo.pageNow = this.pageInfo.pageNow + 1;
          },
          error => {
            this.$router.push("/home");
            if (error.status == 401) {
              this.$notify({
                message: "没有登陆，不可以发表文章"
              });
              return;
            }
            this.$notify({
              message: "程序异常：" + error.status + "，请联系管理员"
            });
          }
        );
    }
  },
  showAddItem: function() {
    this.dialogFormVisible = true;
  },
  addItem: function() {
    // 添加新文件或修改title
    this.loading = true;
    if (!this.titleInfo.title) {
      this.loading = false;
      this.$notify({
        title: "成功",
        message: "成功",
        type: "success"
      });
      return;
    }
    //先判断content是否有值
    if (!this.titleInfo.content) {
      this.titleInfo.content = "";
    }
    if (!this.titleInfo.imgs) {
      this.titleInfo.imgs = "";
    }
    this.titleInfo.type = this.pageInfo.type;
    this.$http
      .post("/api/content/update", this.titleInfo, {
        headers: {
          token: this.token
        }
      })
      .then(
        res => {
          this.loading = false;
          var dataJ = res.body;
          if (dataJ.code === 1) {
            this.$message.error(dataJ.msg);
            return false;
          }
          //调接口保存
          if (!this.titleInfo.id) {
            this.contents.unshift(dataJ.data);
          }
          this.dialogFormVisible = false;
          this.titleInfo = {};
          this.$notify({
            title: "成功",
            message: dataJ.msg,
            type: "success"
          });
        },
        error => {
          this.loading = false;
          if (error.status == 401) {
            this.$notify({
              title: "失败",
              message: "toekn失效请重新登录"
            });
            this.$router.push("/home");
            return;
          }
          this.$notify({
            title: "失败",
            message: "程序异常：" + error.status + "，请联系管理员"
          });
        }
      );
  },
  //onEditorBlur(quill) {
  //  console.log("换行", quill)
  //},
  //onEditorFocus(quill) {
  //  console.log("获取焦点", quill)
  //},
  onEditorReady(quill) {
    console.log("加载!", quill);
  },
  //onEditorChange({ quill, html, text }) {
  //  console.log("editor change!", quill, html, text)
  //  this.content = html
  //},
  showContent(item) {
    this.contentInfo = item;
    this.disabled = false;
    this.$notify({
      message: "编辑模式已开启"
    });
  },
  remove: function(item) {
    this.$confirm("此操作将永久删除该文件, 是否继续?", "解忧杂货铺提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      if (!item.id) {
        return;
      }
      //调用接口
      this.$http
        .get("/api/content/del/" + item.id, {
          headers: {
            token: this.token
          }
        })
        .then(
          response => {
            //移除dom元素
            var index = this.contents.indexOf(item);
            this.contents.splice(index, 1);
            this.$notify({
              title: "成功",
              message: response.body.msg,
              type: "success"
            });
          },
          error => {
            this.$notify({
              title: "失败",
              message:
                "程序异常：" + JSON.stringify(error.status) + "，请联系管理员"
            });
          }
        );
    });
  },
  updateTitle: function(item) {
    this.dialogFormVisible = true;
    this.titleInfo = item;
  },
  saveInfo: function() {
    // 调用修改接口
    if (!this.contentInfo.id) {
      this.$notify({
        title: "错误",
        message: "数据有误"
      });
    }
    this.loading = true;
    this.$http
      .post("/api/content/update", this.contentInfo, {
        headers: {
          token: this.token
        }
      })
      .then(
        res => {
          this.loading = false;
          var dataJ = res.body;
          if (dataJ.code === 1) {
            this.$message.error(dataJ.msg);
            return;
          }
          //调接口保存
          this.$notify({
            title: "成功",
            message: dataJ.msg,
            type: "success"
          });
        },
        error => {
          this.loading = false;
          if (error.status == 401) {
            this.$notify({
              title: "失败",
              message: "toekn失效请重新登录"
            });
            this.$router.push("/home");
            return;
          }
          this.$notify({
            title: "失败",
            message: "程序异常：" + error.status + "，请联系管理员"
          });
        }
      );
  },
  mounted() {
    console.log("this is current quill instance object", this.editor);
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    }
  },
  filters: {
    toTime: function(time) {
      var today = new Date(time);
      return today.Format("yyyy-MM-dd");
    }
  }
};
</script>

<style lang="stylus" rel="stylesgeet/stylus" >
#work
  width:100%;
  height: 100vh;
  #work_title,#work_editor
    float:left
  #work_title
    width:20%
    .work_title_div
      background-color:#fff
      OVERFLOW-Y: auto
      OVERFLOW-X: hidden
      height: 100vh
      .work_title_much
        height:90px
        padding:0 20px 0 20px
        border-bottom: 1px #ccc solid
        .work_title_much_title
          height:90px
          width:100%
          font-size:14px
          div
            width:100%
          .work_title_much_title_div1
            overflow: hidden
            text-overflow:ellipsis
            white-space: nowrap
            height: 40px
            line-height: 58px
          .work_title_much_title_div1:hover
            color:#63B8FF
          .work_title_much_title_div3
            width:100%
            text-align: right
            margin-right:15px
            span:first-child
              margin-right:10px
            span:first-child:hover
              color:#00BFFF
            span:nth-child(2)
              margin-right:10px
            span:nth-child(2):hover
              color:red
      .work_title_much:hover
        cursor:pointer
        background-color:#e6e6e6
  #work_editor
    width:80%
    background-color:#fff
    height:100vh
    .quill-editor
      height:calc(100% - 44px)
  .work_title_add
    background-color: #fff
    font-size:20px
    position:absolute
    width:30px
    height:30px
    bottom:50px
    right:70px
    line-height: 30px
    text-align: center
    border-radius:30px
  .work_title_add,.work_title_download,.work_title_save:hover
    cursor:pointer
  .work_title_save
    background-color: #fff
    font-size:20px
    position:absolute
    width:30px
    height:30px
    bottom:50px
    right:110px
    line-height: 30px
    text-align: center
    border-radius:30px
  .work_title_download
    font-size:20px
    position:absolute
    bottom:50px
    right:30px
    width: 30px
    height: 30px
    background-color: #fff
    text-align: center
    line-height: 30px
    border-radius:30px
</style>
